<template>
    <view class="page padding30">
        <block v-for="(item,index) in formData" :key="index">
            <!-- 单行输入框 -->
            <view class="list padding20" :class="{'required': item.required}" v-if="item.type == 'input'">
                <view class="color_80">{{ item.title }}</view>
                <input class="m-top20" v-model="item.value" :placeholder="item.placeholder" />
            </view>

            <!-- 数字输入框 -->
            <view class="list mini d-flex a-center" :class="{'required': item.required}" v-if="item.type == 'number'">
                <view class="color_80">{{ item.title }}：</view>
                <input class="flex-1" type="number" v-model="item.value" :placeholder="item.placeholder" />
            </view>

            <!-- 带小数点的数字 -->
            <view class="list mini d-flex a-center" :class="{'required': item.required}" v-if="item.type == 'money'">
                <view class="color_80">{{ item.title }}：</view>
                <input class="flex-1" type="digit" v-model="item.value" :placeholder="item.placeholder" />
            </view>

            <!-- 文本域 -->
            <view class="list padding20" :class="{'required': item.required}" v-if="item.type == 'textarea'">
                <view class="color_80">{{ item.title }}</view>
                <textarea class="wh h6 m-top20" v-model="item.value" :placeholder="item.placeholder" :maxlength="-1" auto-height disable-default-padding />
            </view>

            <!-- 上传图片 -->
            <view class="list padding20" :class="{'required': item.required}" v-if="item.type == 'img'">
                <view class="color_80">{{ item.title }}</view>
                <view class="row">
                    <block v-if="item.value.length">
                        <view class="p-re" v-for="(subItem,subIndex) in item.value" :key="subIndex">
                            <image :src="$imgUrls(subItem)" mode="aspectFill" class="upload"></image>
                            <image src="../../static/close.png" class="close bgwhite bor_radius" @click="delImg(index, subIndex)"></image>
                        </view>
                    </block>
                    <image src="../../static/upload.png" class="upload" @click="uploadImage(item.num - item.value.length, index)" v-if="item.value.length < item.num"></image>
                </view>
            </view>

            <!-- 单选 -->
            <view class="list padding20" :class="{'required': item.required}" v-if="item.type == 'radio'">
                <view class="color_80">{{ item.title }}</view>
                <view class="row">
                    <view class="d-flex a-center m-top20 m-right40" @click="radioBtn(index, subItem.value)" v-for="(subItem,subIndex) in item.data" :key="subIndex">
                        <view class="radioRound m-right10 p-re" :class="{'active': item.value == subItem.value}"></view>
                        <view>{{ subItem.name }}</view>
                    </view>
                </view>
            </view>

            <!-- 日期时间选择器(范围) -->
            <view class="list padding20" :class="{'required': item.required}" v-if="item.type == 'datetime_interval'">
                <view class="color_80">{{ item.title }}</view>
                <view class="row m-top20">
                    <time-picker @btnConfirm="btnConfirm($event, index, 0)">
                        <view>{{ item.value[0] || '开始时间' }}</view>
                    </time-picker>
                    <view class="m-left10 m-right10">-</view>
                    <time-picker @btnConfirm="btnConfirm($event, index, 1)">
                        <view>{{ item.value[1] || '结束时间' }}</view>
                    </time-picker>
                </view>
            </view>

            <!-- 富文本 -->
            <view class="list padding20" :class="{'required': item.required}" v-if="item.type == 'richtext'">
                <view class="color_80">{{ item.title }}</view>
                <sp-editor :toolbar-config="toolbarConfig" @init="initEditor($event, item.value)" @upinImage="upinImage" @input="inputOver($event, index)"></sp-editor>
            </view>
        </block>
        
        <view class="d-flex j-sa m-top80">
            <!-- <view class="bot_btn flexac color_99">重置</view> -->
            <view class="bot_btn flexac white" @click="submit">提交</view>
        </view>
    </view>
</template>

<script>
    // H5 不支持从微信聊天会话中选择文件

    export default {
        data() {
            return {
                formData: [],
                editorIns: null, // 编辑器实例
                toolbarConfig: {
                    excludeKeys: ['direction', 'listCheck', 'export'],
                    iconSize: '14px'
                },
                orderId: '0' // 表单id、0为添加
            }
        },
        onLoad(e) {
            if(e.order_id) this.orderId = e.order_id
            this.getInfo()
        },
        methods: {
            getInfo() {
                this.$http.post({
                    url: '/SRA_CustomerForm/getAppointmentFormItemInfo',
                    data: {
                        bid: uni.getStorageSync('bid'),
                        shop_id: uni.getStorageSync('store_id'),
                        orderId: this.orderId
                    }
                }).then(res => {
                    if(res.code != 100) return this.$Toast(res.msg)
                    this.formData = res.data || []
                })
            },
            uploadImage(count, index) {
                uni.chooseImage({
                    count,
                    success: res => {
                        res.tempFilePaths.forEach(item => {
                            this.$common.uploadFiles(item).then(result => {
                                if(result.errcode != 100) return this.$Toast('上传失败')
                                let Url = result.url.slice(22)
                                this.formData[index].value.push(Url)
                            })
                        })
                    }
                })
            },
            delImg(index, subIndex) {
                this.formData[index].value.splice(subIndex, 1)
            },
            radioBtn(index, value) {
                this.formData[index].value = value
            },
            btnConfirm(e, index, subIndex) {
                this.$set(this.formData[index].value, subIndex, e.key)
            },
            initEditor(editor, value) {
                this.editorIns = editor
                let html = this.addDomain(value || '')
                this.editorIns.setContents({ // 初始化编辑器内容
                    html
                })
            },
            addDomain(html) { // 给图片拼接域名
                let reg = /<img [^>]*src=['"]([^'"]+)[^>]*>/g
                return html.replace(reg, (match, url) => {
                    if(url.search(/^(http|https)/) > -1) return match
                    return match.replace(url, this.imgUrl + url)
                })
            },
            upinImage(tempFiles, editorCtx) {
                tempFiles.forEach(item => {
                    this.$showLoading('上传中请稍后')
                    this.$common.uploadFiles(item.path).then(res => {
                        if(res.errcode != 100) return this.$Toast('上传失败')
                        let Url = res.url.slice(22)
                        editorCtx.insertImage({
                            src: this.$imgUrls(Url),
                            width: '80%',
                            success: () => {
                                this.$hideLoading()
                            }
                        })
                    })
                })
            },
            inputOver(e, index) { // 获取已编辑的内容
                this.formData[index].value = e.html
            },
            submit() {
                console.log(this.formData)
                let data = {
                    bid: uni.getStorageSync('bid'),
                    uid: uni.getStorageSync('uid'),
                    shop_id: uni.getStorageSync('store_id'),
                    orderId: this.orderId
                }
                let result = this.formData.find(item => item.required && (!item.value || !item.value.length))
                if(result) return this.$Toast(result.title + '不能为空')

                this.formData.forEach(item => {
                    if(item.type == 'img') { // 图片
                        data[item.field_name] = item.value.join()
                    } else if(item.type == 'datetime_interval') { // 日期时间范围
                        data[item.field_name] = item.value.join(' - ')
                    } else {
                        data[item.field_name] = item.value
                    }
                })
                console.log(data)

                this.$http.post({
                    url: '/SRA_CustomerForm/addStoreAppointmentForm',
                    data
                }).then(res => {
                    this.$Toast(res.msg)
                    if(res.code != 100) return
                    if(this.orderId == 0) this.orderId = res.data
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
    .list {
        background: #fff;
        border-radius: 10rpx;
        padding-left: 40rpx;
        margin-bottom: 20rpx;
        position: relative;
        &.mini {
            height: 80rpx;
        }
    }
    .required::before {
        content: '*';
        font-size: 40rpx;
        color: $color;
        position: absolute;
        left: 10rpx;
        top: 10rpx;
    }
    .upload {
        width: 130rpx;
        height: 130rpx;
        border-radius: 8rpx;
        margin: 20rpx 20rpx 0 0;
    }
    .close {
        width: 36rpx;
        height: 36rpx;
        position: absolute;
        top: 6rpx;
        right: 14rpx;
        z-index: 10;
    }
    .radioRound {
        width: 28rpx;
        height: 28rpx;
        border: 1rpx solid #ddd;
        border-radius: 50%;
        &.active {
            border: 1rpx solid $color;
            &::after {
                content: '';
                width: 12rpx;
                height: 12rpx;
                background: $color;
                border-radius: 50%;
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
    .bot_btn {
        width: 260rpx;
        height: 80rpx;
        border-radius: 10rpx;
        font-size: 30rpx;
        letter-spacing: 6rpx;
        &:first-child {
            background: #EAEAEA;
        }
        &:last-child {
            background: $color;
        }
    }
</style>